package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entiey.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String UPDATE_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";

    @Autowired
    private SkuService skuService;

    @Resource
    private SkuMapper skuMapper;

    //根据spuID查询sku的集合
    @Override
    public List<Sku> querySkuDTOListById(Long id) {
        return skuService.query().eq("spu_id", id).list();
    }

    /**
     * 扣减库存
     * @param cartMap 商品集合
     */
    @Override
    public void deductStock(Map<Long, Integer> cartMap) {

        //方案一
        //遍历sku
        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            //调用方法
            HashMap<String, Object> param = new HashMap<>();
            param.put("id",skuId);
            param.put("num",num);
            int count = getBaseMapper().deductStock(param);
            if (count == 0){
                //更新失败
                throw new LyException(400,"更新库存失败！");
            }
        }

        //方案二
        /*executeBatch(sqlSession ->  {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                Long skuId = entry.getKey();
                Integer num = entry.getValue();
                //调用方法
                HashMap<String, Object> param = new HashMap<>();
                param.put("id", skuId);
                param.put("num", num);
                sqlSession.update(UPDATE_STOCK_STATEMENT, param);
            }
            //刷新和提交
            sqlSession.flushStatements();
        });*/

    }

}